/**
 * tab切换封装
 * @Author: linzy
 * @Date: 2022-07-19
 * @function useTabs
 * @param {tabs[]} tabs - tabs数组 [{ label: "xxx", value: "xxx" }]
 * @param {buttons[]} buttons - tabs 右侧按钮
 * @param {*} ... - antd Tabs组件的属性
 * @returns [tabs, tabProps];
 * @example
  import { useTabs } from "@/hooks";
  const [Tabs, tabsProps] = useTabs({
    tabs: [
      { label: "xxx1", value: "xxx1" },
      { label: "xxx2", value: "xxx2" },
    ],
    defaultActiveKey: tabId,
    onChange(val) {
      // btnClick("tab", val);
    }
  });
  <Tabs {...tabsProps}></Tabs>
 */
import { Tabs } from "antd";
import { useButtons } from "@/hooks";
const { TabPane } = Tabs;
import { typeOf } from "@/hooks/tools";
import { setDefaultAttrs } from "@/hooks/tools";

const tabs = props => {
  const { tabs = [], buttons, ...tabsProps } = props;
  let list = [];
  if (tabs && tabs.length) {
    list = tabs.map(item => {
      var obj = {};
      if (typeOf(tabs[0]) === "string") {
        obj.label = item;
        obj.value = item;
      } else {
        obj.label = item.tab ?? item.label;
        obj.value = item.key ?? item.value;
        obj.children = item.children;
      }
      return obj;
    });
  }
  if (buttons) {
    tabsProps.tabBarExtraContent = useButtons({ buttons });
  }
  setDefaultAttrs(tabsProps, { defaultActiveKey: list[0]?.value });
  return (
    <Tabs {...tabsProps}>
      {tabsProps.children
        ? tabsProps.children
        : list.map((item, index) => {
            const { label, value, children } = item;
            return (
              <TabPane tab={label} key={value}>
                {children}
              </TabPane>
            );
          })}
    </Tabs>
  );
};

export default props => {
  return [tabs, props];
};
